package io.wdb.modules.generator.generator.controller.api;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.relaxng.datatype.DatatypeStreamingValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.Constants;

import io.wdb.common.utils.Constant;
import io.wdb.common.utils.DateUtils;
import io.wdb.common.utils.R;
import io.wdb.common.utils.RedisUtils;
import io.wdb.modules.generator.generator.entity.statistics.PermissionApp;
import io.wdb.modules.generator.generator.entity.web.BaseResponse;
import io.wdb.modules.generator.generator.entity.web.DaysQueryRequest;
import io.wdb.modules.generator.generator.entity.web.OperationResponse;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.StatementResponse;
import io.wdb.modules.generator.generator.entity.web.StatisticsDetailResponse;
import io.wdb.modules.generator.generator.entity.web.UserOperationCurveResponse;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.StatementService;
import io.wdb.modules.manager.sys.entity.SysMenuEntity;
import io.wdb.modules.manager.sys.entity.SysUserEntity;
import io.wdb.modules.manager.sys.service.SysMenuService;
import io.wdb.modules.manager.sys.shiro.ShiroUtils;
import io.wdb.modules.manager.sys.shiro.UidToken;

@RestController
@RequestMapping("statement")
public class StatementController extends BaseController{
	
	@Autowired
	private StatementService statementService;
	
	@Autowired
    private RedisUtils redisUtils;
	
	@Value(value = "${server.port}")
	public String redisPath;
	
	/**
	 * 固定时间段客流量
	 */
	@RequestMapping("/newUserOrOrders")
	//@RequiresPermissions("statement:newUserOrOrders")
	public BaseResponse newUserOrOrders(@RequestParam Map<String, Object> params){
		BaseResponse baseResponse = success();
		List<StatementResponse> statementResponses = new ArrayList<StatementResponse>();

		String redisKey_dayOrders =  redisPath+"dayOrders";
		String redisKey_accountCash =  redisPath+"accountCash";
		String redisKey_dayNewCustomers =  redisPath+"dayNewCustomers";
		
		int rows = 7;
		
		String dayNewCustomers_r = null;
		String dayOrders_r = null; 
		String accountCash_r = null; 
		
		int dayNewCustomers = 0;
		int dayOrders = 0 ;
		int accountCash = 0 ;
        //时间 -- 数量
        for(int i = rows; i > 0; i--) {
        	Calendar c = Calendar.getInstance(); 
        	StatementResponse response = new StatementResponse();
        	c.add(Calendar.DATE, - i);  
        	String dateStr = DateUtils.format(c.getTime(), DateUtils.DATE_MONTH_DAY);
            dayOrders_r = redisUtils.get(redisKey_dayOrders + dateStr);
            accountCash_r = redisUtils.get(redisKey_accountCash + dateStr);
            dayNewCustomers_r = redisUtils.get(redisKey_dayNewCustomers + dateStr);
            //新增客户
            if(dayNewCustomers_r == null) {
            	 params.put("current_time", c.getTime());
            	 dayNewCustomers = statementService.getNewUserRiseByTime(params);
            	 redisUtils.set(redisKey_dayNewCustomers + dateStr, dayNewCustomers, RedisUtils.NOT_EXPIRE);
            }else {
            	dayNewCustomers = new Integer(dayNewCustomers_r);
            }
            //新增订单
            if(dayOrders_r == null) {
           	params.put("current_time", c.getTime());
           	dayOrders = statementService.getOrdersByTime(params);
           	 
           	 redisUtils.set(redisKey_dayOrders + dateStr, dayOrders, RedisUtils.NOT_EXPIRE);
           }else {
        	   dayOrders = new Integer(dayOrders_r);
           }
            //新缴押金
            if(accountCash_r == null) {
           	 params.put("current_time", c.getTime());
           	 accountCash = statementService.getAccountCashByTime(params);
           	 redisUtils.set(redisKey_accountCash + dateStr, accountCash, RedisUtils.NOT_EXPIRE);
           }else {
        	   accountCash = new Integer(accountCash_r);
           }
            
            response.setDate_str(dateStr);
			response.setAdd_person(dayNewCustomers);
			
			response.setDeposit(accountCash);
			response.setBorrow_ordes(dayOrders);
			statementResponses.add(response);
        }
		baseResponse.setItems(statementResponses);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:totalStatistics
	 * @Description:总计统计
	 * @Time 2018年2月8日 上午11:29:15
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/totalStatistics")
	@RequiresPermissions("statement:total")
	public BaseResponse totalStatistics(){
		BaseResponse baseResponse = success();
		List<OperationResponse> operationResponses = statementService.totalStatistics();
		baseResponse.setDetail(operationResponses);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:eachDayStatistics
	 * @Description:今日新增数据统计
	 * @Time 2018年2月8日 下午4:42:03
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/daysStatistics")
	@RequiresPermissions("statement:today:list")
	public BaseResponse todayStatistics(DaysQueryRequest daysQueryRequest){
		BaseResponse baseResponse = success();
		List<OperationResponse> operationResponses = statementService.currentDayStatistics(daysQueryRequest);
		baseResponse.setDetail(operationResponses);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:daysEachStatistics
	 * @Description:用户数据分时段统计显示
	 * @Time 2018年2月11日 下午4:59:05
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/daysEachStatistics")
	@RequiresPermissions("statement:user:list")
	public BaseResponse daysEachStatistics(DaysQueryRequest daysQueryRequest){
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		//时间的处理
		List<OperationResponse> operationResponses = statementService.daysUserTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		List<UserOperationCurveResponse> timeDetailData = statementService.daysUserTimeDetailDataStatistics(daysQueryRequest);
		detailResponse.setTimeDetailData(timeDetailData);
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.daysUserEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		
		return baseResponse;
	}
	/**
	 * 
	 * @Method:daysEachStatistics
	 * @Description:用户维度年龄段统计
	 * @Time 2018年2月11日 下午4:59:05
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/daysAgeUsers")
	@RequiresPermissions("statement:user:list")
	public BaseResponse daysAgeUsers(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		//时间的处理
		List<OperationResponse> operationResponses = statementService.daysAgeUserTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		List<UserOperationCurveResponse> timeDetailData = statementService.daysAgeUserTimeDetailDataStatistics(daysQueryRequest);
		detailResponse.setTimeDetailData(timeDetailData);
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.dayAgesUserEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:labelBooks
	 * @Description:各个标签借阅情况
	 * @Time 2018年4月2日 下午3:48:42
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/daysLabelBooks")
	@RequiresPermissions("statement:user:list")
	public BaseResponse daysLabelBooks(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		//时间的处理
		List<OperationResponse> operationResponses = statementService.daysLabelBooksTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		List<UserOperationCurveResponse> timeDetailData = statementService.daysLabelBooksTimeDetailDataStatistics(daysQueryRequest);
		detailResponse.setTimeDetailData(timeDetailData);
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.dayLabelBooksEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:daysAgeBooks
	 * @Description:按年龄节点书本维度的统计
	 * @Time 2018年4月2日 上午11:55:18
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/daysAgeBooks")
	@RequiresPermissions("statement:user:list")
	public BaseResponse daysAgeBooks(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		//时间的处理
		List<OperationResponse> operationResponses = statementService.daysAgeBookTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		List<UserOperationCurveResponse> timeDetailData = statementService.daysBookUserTimeDetailDataStatistics(daysQueryRequest);
		detailResponse.setTimeDetailData(timeDetailData);
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.daysBookUserEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		return baseResponse;
	}
	
	/**
	 * 
	 * @Method:daysCapitalEachStatistics
	 * @Description:用户资金数据分时段统计显示
	 * @Time 2018年2月27日 上午10:18:08
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/daysCapitalEachStatistics")
	@RequiresPermissions("statement:capital:list")
	public BaseResponse daysCapitalEachStatistics(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		List<OperationResponse> operationResponses = statementService.daysCapitalTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		List<UserOperationCurveResponse> timeDetailData = statementService.daysCapitalTimeDetailDataStatistics(daysQueryRequest);
		detailResponse.setTimeDetailData(timeDetailData);
		
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.daysCapitalEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		
		return baseResponse;
	}
	/**
	 * 
	 * @Method:bookStatistics
	 * @Description:书籍数据分时段统计
	 * @Time 2018年3月6日 上午10:28:55
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/bookStatistics")
	@RequiresPermissions("statement:books:list")
	public BaseResponse bookStatistics(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		List<OperationResponse> operationResponses = statementService.bookTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.bookEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		return baseResponse;
	}
	
	/**
	 * 
	 * @Method:daysBookShelfEachStatistics
	 * @Description:书柜数据分时段统计显示
	 * @Time 2018年2月28日 下午1:43:23
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/daysBookShelfEachStatistics")
	@RequiresPermissions("statement:bookshelf:list")
	public BaseResponse daysBookShelfEachStatistics(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		
		List<OperationResponse> operationResponses = statementService.daysBookShelfTotalStatistics(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		
		List<UserOperationCurveResponse> timeDetailData = statementService.daysBookShelfTimeDetailDataStatistics(daysQueryRequest);
		detailResponse.setTimeDetailData(timeDetailData);
		baseResponse.setDetail(detailResponse);
		List<UserOperationCurveResponse> curveResponse = statementService.daysBookShelfEachStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponse);
		
		return baseResponse;
	}
	/**
	 * 
	 * @Method:bookShelfCurrentCondition
	 * @Description:书柜当前状态结果
	 * @Time 2018年3月1日 下午4:46:49
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/bookShelfCurrentCondition")
	@RequiresPermissions("statement:bookshelf:condition")
	public BaseResponse bookShelfCurrentCondition(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		if(daysQueryRequest.getBookShelfCode()==null||"".equals(daysQueryRequest.getBookShelfCode().trim())) {
			WebResponse response = new WebResponse();
			response.setCode(ResponseEnum.SHELF_CODE_IS_NULL.getCode());
			response.setMessage("请先选定某个书柜");
			baseResponse.setDetail(response);
			return baseResponse;
		}
		StatisticsDetailResponse detailResponse = new StatisticsDetailResponse();
		List<OperationResponse> operationResponses = statementService.bookShelfCurrentCondition(daysQueryRequest);
		detailResponse.setTotalData(operationResponses);
		baseResponse.setDetail(detailResponse);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:bookShelfEntityBorrowStatistics
	 * @Description:书本出借情况统计
	 * @Time 2018年3月2日 上午10:37:52
	 * @author: Tom
	 * @param daysQueryRequest
	 * @return
	 */
	@RequestMapping("/bookShelfEntityBorrowStatistics")
	@RequiresPermissions("statement:bookshelf:books")
	public BaseResponse bookShelfEntityBorrowStatistics(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		if(daysQueryRequest.getBookShelfCode()==null||"".equals(daysQueryRequest.getBookShelfCode().trim())) {
			baseResponse.setResult(0);
			baseResponse.setCode(ResponseEnum.SHELF_CODE_IS_NULL.getCode());
			baseResponse.setMessage("请先选定某个书柜");
			return baseResponse;
		}
		List<UserOperationCurveResponse> curveResponses = statementService.bookShelfEntityBorrowStatistics(daysQueryRequest);
		baseResponse.setItems(curveResponses);
		return baseResponse;
	}
	/**
	 * 
	 * @Method:bookShelfAgeBooksStatistics
	 * @Description:各年龄段出借书籍统计
	 * @Time 2018年3月2日 上午10:54:35
	 * @author: Tom
	 * @return
	 */
	@RequestMapping("/bookShelfAgeBooksStatistics")
	@RequiresPermissions("statement:bookshelf:ages")
	public BaseResponse bookShelfAgeBooksStatistics(DaysQueryRequest daysQueryRequest) {
		BaseResponse baseResponse = success();
		if(daysQueryRequest.getBookShelfCode()==null||"".equals(daysQueryRequest.getBookShelfCode().trim())) {
			baseResponse.setResult(0);
			baseResponse.setCode(ResponseEnum.SHELF_CODE_IS_NULL.getCode());
			baseResponse.setMessage("请先选定某个书柜");
			return baseResponse;
		}
		List<UserOperationCurveResponse> curveResponses = statementService.bookShelfAgeBooksStatistics(daysQueryRequest);
		baseResponse.setDetail(curveResponses);
		return baseResponse;
	}
	@Autowired
	private SysMenuService sysMenuService;
	/**
	 * 
	 * @Method:listApp
	 * @Description:app端用户拥有权限返回
	 * @Time 2018年3月15日 上午10:30:25
	 * @author: Tom
	 * @param params
	 * @return
	 */
	@RequestMapping("/listApp")
	public BaseResponse listApp(@RequestParam Map<String, Object> params){
		BaseResponse baseResponse = success();
		SysUserEntity entity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
		if(entity==null) {
			throw new UnauthenticatedException();
		}
		Long userId = entity.getUserId();
		if(userId != Constant.SUPER_ADMIN){
			params.put("createUserId", userId);
		}
		List<SysMenuEntity> menuList = sysMenuService.queryList(params);
		List<PermissionApp> list = new ArrayList<PermissionApp>();
		for(SysMenuEntity sysMenuEntity:menuList) {
			PermissionApp app =new PermissionApp();
			app.setName(sysMenuEntity.getName());
			app.setPermission(sysMenuEntity.getPerms());
			list.add(app);
		}
		baseResponse.setItems(list);
		return baseResponse;
	}
	/**
	 * 登录
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public BaseResponse login(String username, String password, String captcha,String uid)throws IOException {
		BaseResponse baseResponse = success();
		WebResponse webResponse = new WebResponse();
		Session session = null;
		try{
			Subject subject = ShiroUtils.getSubject();
			if(uid!=null&&!"".equals(uid)) {
				UidToken token = new UidToken("",uid,uid);
				subject.login(token);
			}else {
				if(captcha.equals("wdbbang")) {
					System.out.println("跳过");
				}else {
					String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
				}
				UidToken token = new UidToken(username, password,null);
				subject.login(token);
			}
			session = subject.getSession();
			session.getId();
			webResponse.setCode(100);
			webResponse.setMessage(session.getId()+"");
			baseResponse.setDetail(webResponse);
		}catch (UnknownAccountException e) {
			baseResponse.setResult(0);
			baseResponse.setCode(3);
			baseResponse.setMessage("账号或密码不正确");
			return baseResponse;
		}catch (IncorrectCredentialsException e) {
			baseResponse.setResult(0);
			baseResponse.setCode(3);
			baseResponse.setMessage("账号或密码不正确");
			return baseResponse;
		}catch (LockedAccountException e) {
			baseResponse.setResult(0);
			baseResponse.setCode(3);
			baseResponse.setMessage("账号已被锁定,请联系管理员");
			return baseResponse;
		}catch (AuthenticationException e) {
			baseResponse.setResult(0);
			baseResponse.setCode(3);
			baseResponse.setMessage("账号已被锁定,请联系管理员");
			return baseResponse;
		}
		return baseResponse;
	}
}

